#include "global.h"
#include "client_socket.h"
#include "client_http.h"

char *HTTPClient()
{
    char *httpClient = NULL;

    httpClient = (char *)malloc(sizeof(char) * CLIENTSIZE);
    if (httpClient == NULL)
    {
        exit(-1);
    }
    memset(httpClient, 0, CLIENTSIZE);

    return httpClient;
}

char *HTTPRequest(char *httpClient, char *content, int sock, char *method, char *url, char *host, char *contentType)
{
    int res = 0;
    char *httpHead = NULL;

    httpHead = HTTPHead(method, url, host, contentType, strlen(content));
    strcat(httpClient, httpHead);
    strcat(httpClient, content);
    strcat(httpClient, "\r\n\r\n");
    FreeHTTPHead(httpHead);
    res = write(sock, httpClient, strlen(httpClient));
    if (res < 0)
    {
        exit(-1);
    }
    res = read(sock, httpClient, CLIENTSIZE);
    close(sock);
    return httpClient;
}

char *HTTPHead(char *method, char *url, char *host, char *contentType, int len)
{
    int digit = 0;
    char *contentLength = NULL;
    char *httpHead =  NULL;

    httpHead = (char *)malloc(sizeof(char) * HEADSIZE);
    if (httpHead == NULL)
    {
        exit(-1);
    }
    memset(httpHead, 0, HEADSIZE);

    digit = NumDigit(len);
    contentLength = (char *)malloc(sizeof(char) * digit);
    if (contentLength == NULL)
    {
        exit(-1);
    }

    strcat(httpHead, method);
    strcat(httpHead, " ");
    strcat(httpHead, url);
    strcat(httpHead, " ");
    strcat(httpHead, "HTTP/1.1\n");
    strcat(httpHead, "Host: ");
    strcat(httpHead, host);
    strcat(httpHead, "\n");
    strcat(httpHead, "Content-Type: ");
    strcat(httpHead, contentType);
    strcat(httpHead, "\n");
    strcat(httpHead, "Content-Length: ");
    sprintf(contentLength, "%d", len);
    strcat(httpHead, contentLength);
    Free(contentLength);
    strcat(httpHead, "\n\n");
    return httpHead;
}

int FreeHTTPClient(char *httpClient)
{
    if (httpClient != NULL)
    {
        free(httpClient);
        httpClient = NULL;
    }
    return 1;
}

int FreeHTTPHead(char *httpHead)
{
    if (httpHead != NULL)
    {
        free(httpHead);
        httpHead = NULL;
    }
    return 1;
}

int Free(char *heap)
{
    if (heap != NULL)
    {
        free(heap);
        heap = NULL;
    }
    return 1;
}

int NumDigit(int num)
{
    int digit = 0;

    while (num)
    {
        digit++;
        num = num / 10;
    }
    return digit;
}
